<script src="{{ cdnjs }}jquery/3.4.1/jquery.min.js"></script>
<script src="{{ cdnjs }}twitter-bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script src="{{ cdnjs }}js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="{{ cdnjs }}jquery.scrollbar/0.2.11/jquery.scrollbar.min.js"></script>
<script src="{{ cdnjs }}jquery-scroll-lock/3.1.3/jquery-scrollLock.min.js"></script>
<script src="{{ cdnjs }}notyf/3.2.0/notyf.min.js"></script>
<script>
    $.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}'}});

    var notyf = new Notyf({position: {x: 'right', y: 'top'}});

    var notifications = [];

    function KZ_Loading(config) {
        if (this instanceof KZ_Loading) {
            const domTemplate = '<div class="modal kz-loading" data-kzid="@@KZ_Loadin_ID@@" backdrop="static" keyboard="false"><div style="width: 200px;height:20px; z-index: 20000; position: absolute; text-align: center; left: 50%; top: 50%;margin-left:-100px;margin-top:-10px"><div class="progress progress-striped active" style="margin-bottom: 0;"><div class="progress-bar" style="width: 100%;"></div></div><h5>@@KZ_Loading_Text@@</h5></div></div>';
            this.config = {
                content: 'loading...',
                time: 0,
            };
            if (config != null) {
                if (typeof config === 'string') {
                    this.config = Object.assign(this.config, {
                        content: config
                    });
                } else if (typeof config === 'object') {
                    this.config = Object.assign(this.config, config);
                }
            }
            this.id = new Date().getTime().toString();
            this.state = 'hide';

            /*显示 */
            this.show = function () {
                $('.kz-loading[data-kzid=' + this.id + ']').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                this.state = 'show';
                if (this.config.time > 0) {
                    var that = this;
                    setTimeout(function () {
                        that.hide();
                    }, this.config.time);
                }
            };
            /*隐藏 */
            this.hide = function (callback) {
                $('.kz-loading[data-kzid=' + this.id + ']').modal('hide');
                this.state = 'hide';
                if (callback) {
                    callback();
                }
            };
            /*销毁dom */
            this.destroy = function () {
                var that = this;
                this.hide(function () {
                    var node = $('.kz-loading[data-kzid=' + that.id + ']');
                    node.next().remove();
                    node.remove();
                    that.show = function () {
                        throw new Error('对象已销毁！');
                    };
                    that.hide = function () {
                    };
                    that.destroy = function () {
                    };
                });
            }

            var domHtml = domTemplate.replace('@@KZ_Loadin_ID@@', this.id).replace('@@KZ_Loading_Text@@', this.config.content);
            $('body').append(domHtml);
        } else {
            return new KZ_Loading(config);
        }
    }

    function showNotifications() {
        if (!notifications.length) {
            $("#notification-board").html('<div class="list-group list-group-flush"><ul ' +
                'href="#!" class="list-group-item list-group-item-action"><div class="row ' +
                'align-items-center"><div class="col-auto"><i class="fas ' +
                'fa-check"></i></div><div class="col ml--2 text-sm mb-0"><div class="d-flex ' +
                'justify-content-between align-items-center"><div><h4 class="mb-0 ' +
                'text-sm">消息</h4></div></div><p class="text-sm ' +
                'mb-0">你当前没有消息哟~</p></div></div></ul></div>');
            $("#msg-point").css({"background": "inherit"});
        } else {
            let html = '<div class="px-3 py-3"><h6 class="text-sm text-muted m-0">你有 ' +
                '<strong class="text-primary">' + notifications.length + '</strong> 则消息' +
                '</h6></div><div class="list-group list-group-flush">';
            for (let i = 0; i < notifications.length; i++) {
                html += '<a href="javascript:delNotification(\'' + notifications[i]["timestamp"]
                    + '\')" ' + 'class="list-group-item list-group-item-action"><div ' +
                    'class="row align-items-center"><div class="col-auto"><i class="fas ' +
                    'fa-quote-left"></i></div><div class="col ml--2 text-sm mb-0"><div ' +
                    'class="d-flex justify-content-between align-items-center"><div><h4 ' +
                    'class="mb-0 text-sm">' + escapeString(notifications[i]["label"]) +
                        '</h4></div><div ' +
                    'class="text-right text-muted"><small>' + notifications[i]["time"] +
                    '</small></div></div><p class="text-sm mb-0">' +
                    notifications[i]["content"] + '</p></div></div></a>';
            }
            html += '<div class="px-3 py-3"><h6 class="text-sm text-primary m-0 text-right" ' +
                'style="cursor: pointer" onclick="clearNotification()">清除全部' +
                '</h6></div>'
            $("#notification-board").html(html + '</div>');
            $("#msg-point").css({
                "position": "absolute", "margin-top": "-25px", "margin-left": "15px", "width":
                    "6px", "height": "6px", "background": "red", "border-radius": "50%"
            });
        }
    }

    $.ajax({
        url: "/api/get_notifications/",
        type: "get",
        success: function (res) {
            let data = res;
            if (data["status"]) {
                notifications = data["data"];
                showNotifications();
            } else {
                $("#notification-board").html('<div class="list-group list-group-flush"><ul ' +
                    'href="#!" class="list-group-item list-group-item-action"><div class="row ' +
                    'align-items-center"><div class="col-auto"><i class="fas ' +
                    'fa-exclamation-triangle"></i></div><div class="col ml--2 text-sm mb-0"><div ' +
                    'class="d-flex ' +
                    'justify-content-between align-items-center"><div><h4 class="mb-0 ' +
                    'text-sm">消息</h4></div></div><p class="text-sm ' +
                    'mb-0">获取失败咯~</p></div></div></ul></div>');
            }
        }
    })

    function delNotification(timestamp) {
        $.ajax({
            url: "/api/del_notifications/",
            type: "post",
            dataType: "JSON",
            data: {"time": timestamp},
            success: function (res) {
                if (res.status) {
                    notyf.success(res.msg);
                    for (let i = 0; i < notifications.length; i++) {
                        if (notifications[i]["timestamp"] === timestamp) {
                            notifications.splice(i, 1);
                            break;
                        }
                    }
                    showNotifications();
                } else {
                    notyf.error(res.msg);
                }
            },
            error: function (res) {
                notyf.error("网络错误!");
            }
        })
    }

    function clearNotification() {
        $.ajax({
            url: "/api/clear_notifications/",
            type: "post",
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    notyf.success(res.msg);
                    notifications = [];
                    showNotifications();
                } else {
                    notyf.error(res.msg);
                }
            },
            error: function (res) {
                notyf.error("网络错误!");
            }
        })
    }

    function escapeString(str) {
        var temp = "";
        str = str.toString();
        if (str.length === 0) return "";
        temp = str.replace(/&/g, "&amp;");
        temp = temp.replace(/</g, "&lt;");
        temp = temp.replace(/>/g, "&gt;");
        temp = temp.replace(/\s/g, "&nbsp;");
        temp = temp.replace(/\'/g, "&#39;");
        temp = temp.replace(/\"/g, "&quot;");
        return temp
    }

    {% if error %}
        notyf.error("{{ error }}");
    {% endif %}
</script>